<template>
  <div class="pages online-classroom">
    <div class="pageLevel" v-if="!sub">
     <!--  搜索    -->
      <div class="tableSearch">
        <el-form label-width="100px" class="demo-ruleForm" label-position='left'>
          <el-row>
            <el-col :span='8'>
              <el-form-item label="状态：">
                <el-radio-group v-model="searchData.status" size="small" @change='radioChange'>
                  <el-radio-button v-for='item in statusList' :label="item.id" :key='"status"+item.id'>{{item.name}}</el-radio-button>
                </el-radio-group>
              </el-form-item>
            </el-col>
            <el-col :span='6'>
              <el-form-item label="课程分类:">
                <el-select v-model="searchData.courseType" size="small" style='width: 100%'>
                  <el-option :value='null' label='全部' ></el-option>
                  <el-option v-for="item in courseTypeList" :key="item.id" :value="item.id" :label="item.name"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span='6'>
              <el-form-item label="类型:">
                <el-select v-model="searchData.dataType" size="small"  style='width: 100%'>
                  <el-option label='全部' :value='null'></el-option>
                  <el-option v-for="(item, index) in dataTypeList" :key="'data'+index" :value="index" :label="item"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span='8'>
              <el-form-item label="标题搜索：">
                <el-input class="input" v-model="searchData.title" size="small" placeholder="请输入课程标题"
                          @keyup.enter.native='getTableData(searchData.pageSize, 1)' style='width: 257px' maxlength = '32'></el-input>
              </el-form-item>
            </el-col>
            <el-col :span='8'>
              <el-form-item label="" label-width="0px">
                <el-button type="primary" size="small" @click="getTableData(searchData.pageSize, 1)">查 询</el-button>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </div>
     <!--表格-->
      <div class='table-data'>
        <el-row style='margin-bottom: 20px' type='flex' >
          <h3 style='width: 100px'>课程列表</h3>
          <el-button size="small" @click="routerPush('new')" type="primary" class="addDetail" v-if='setRole("添加课程")'>添加课程</el-button>
        </el-row>
        <el-table :data="tableData" stripe style="width: 100%">
          <el-table-column type="index" label="序号" width="55" align="center"></el-table-column>
          <el-table-column prop="courseType" label="课程分类" align="center">
            <template slot-scope='scope'>{{courseTypeList[scope.row.courseType].name}}</template>
          </el-table-column>
          <el-table-column prop="title" label="名称" align="center" width='300'>
            <template slot-scope='scope'>
              <div class='courseName-column' @mouseenter="mouseEnter(scope.$index, scope.row.status)" @mouseleave="mouseLeave">
                <img :src="scope.row.sImgUrl">
                <div class='courseName-column-txt'>
                  <span>{{scope.row.title}}</span>
                  <p class='tips' v-if='scope.row.status == 0'>更新时间：<br/>{{scope.row.updateTime | toDate}}</p>
                  <p class='tips' v-if='scope.row.status == 1'>发布时间：<br/>{{scope.row.releaseTime | toDate}}</p>
                  <p class='tips' v-if='scope.row.status == 2'>下架时间：<br/>{{scope.row.updateTime | toDate}}</p>
                </div>
                <template v-if='scope.row.status == 2'>
                  <transition name="el-zoom-in-bottom">
                    <div v-show='isActive == scope.$index' class='courseName-mark'>下架原因:{{scope.row.downBecause}}</div>
                  </transition>
                </template>
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="dataType" label="类型" align="center">
            <template slot-scope='scope'>{{dataTypeList[scope.row.dataType]}}</template>
          </el-table-column>
          <el-table-column prop="price" label="价格（元）" align="center">
            <template slot-scope="scope">{{scope.row.price ? scope.row.price : '--'}}</template>
          </el-table-column>
          <el-table-column prop="status" label="状态" align="center">
            <template slot-scope='scope'>{{searchStatus[scope.row.status]}}</template>
          </el-table-column>
          <el-table-column prop="priorityRating" label="权重" align="center" v-if='searchData.status == 1'></el-table-column>
          <el-table-column align="center" label="操作">
            <template slot-scope="scope">
              <template v-if='scope.row.status == 0 || scope.row.status == 2'>
                <el-button size="small" @click="routerPush('edit', scope.row.id)" type="text" class="addDetail" v-if='setRole("添加课程")'>编辑</el-button>
                <el-button size="small" @click="deleCourse(scope.row.id)" type="text" class="addDetail" v-if='setRole("添加课程")'>删除</el-button>
              </template>
              <template v-if='scope.row.status == 1'>
                <el-button size="small" @click="routerPush('see', scope.row.id)" type="text" class="addDetail">查看</el-button>
                <el-button size="small" @click="openDialog(1, scope.row.id)" type="text" class="addDetail" v-if='setRole("下架")'>下架</el-button>
                <el-button size="small" @click="openDialog(2, scope.row.id, scope.row.priorityRating)" type="text" class="addDetail" v-if='setRole("修改权重")'>修改权重</el-button>
              </template>
            </template>
            <template>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <div class="pageblock">
        <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="pageNum" :page-sizes="[5,20,30]" :page-size="pageSize" layout="total, sizes, prev, pager, next, jumper" :total="total"></el-pagination>
      </div>
      <!--      弹框-->
      <el-dialog :title="dialogType == 1 ? '课程下架' : '权重修改'" :visible.sync="courseStopVisible" width="500px" :show-close='false'>
        <el-form  label-width='80px' :model='dialogValue' :rules='ruleDialogValue' class="demo-ruleForm" ref="ratingPriority">
          <el-form-item  label='下架原因' v-if='dialogType == 1'>
            <el-input placeholder='选填（16字以内）' v-model='dialogValue.case' maxlength='16' clearable></el-input>
          </el-form-item>
          <el-form-item  label='设置权重' prop='priority' v-else >
            <el-input style='width: 200px' v-model='dialogValue.priority' maxlength='5'
                      @keyup.native='replace(dialogValue,"priority")' clearable></el-input>
          </el-form-item>
          <el-form-item label='' v-if='dialogType == 2'>
            <p class='tips'>*权重值越大，排序越靠前，权重值为正整数，<br/>可输入范围：0—10000</p>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
            <el-button @click="cancel()">取消</el-button>
            <el-button type="primary" @click="confirmDialog">确定</el-button>
          </span>
      </el-dialog>
    </div>

    <div class="pageLevel" v-else>
      <router-view></router-view>
    </div>
  </div>
</template>

<script>
  import util from '@/util'
  import { mapState } from "vuex";
  import {
    courseInfo,
    offlineAdvCourse,
    coursetype,
    delCourse,
    priorityUpd,
    courseList} from '@/api'
  import Cookies from 'js-cookie'
  export default {
    data() {
      const checkPriorityRating = (rule, value, callback) => {
        if (+value > 10000) {
          return callback(new Error('超过输入范围'));
        } else {
          callback();
        }
      };
      return {
        isActive: null,//鼠标移入当前索引
        total: 0,
        pageSize: 20,
        pageNum: 1,
        courseStopVisible: false, //
        tableData: [],
        searchStatus: ['已保存', '已发布', '已下架'],
        statusList: [{
          name: '全部',
          id: null
        }, {
          name: '已发布',
          id: 1
        }, {
          name: '已保存',
          id: 0
        },{
          name: '已下架',
          id: 2
        },],
        courseTypeList: [], //课程分类列表
        dataTypeList: ['图文','音频', '专辑'], //内容种类列表
        dialogType: null, // 1 下架弹框  2 权重弹框
        currentItem: null, //当前操作课程id
        dialogValue: {
          priority: null, //  权重
          case: '', // 下架原因
        },
        searchData: {
          status: null, //0-已保存 1-已发布 2-已下架
          courseType: null, //0-宝宝喂养 1-宝宝辅食 2-疾病护理 3-学前教育 4-宝贝去哪儿
          dataType: null, //0-图文 1-音频 2-专辑
          title: '',  //课程标题
          pageNum: 1,
          pageSize: 20
        },
        ruleDialogValue: {
          priority: [{required: true, message: '请输入权重', trigger: 'blur'},
            {validator: checkPriorityRating, trigger: 'blur'}], //权重校验
        }
      }
    },
    computed: mapState([
        "sub",
        "power",
        "merchantId",
        "isReLoadData"
      ]),
    watch: {
      sub: {
        handler: function(val, oldVal){
          if (oldVal != null && val == false) {
            this.getTableData(this.pageSize, 1)
          }
        },
        deep: true
      },
      isReLoadData: function(val) {
        if (val == true) {
          let status = util.getQuery('status')
          if(!status && status != 0) {
            this.searchData.status = null
          }else {
            this.searchData.status = status
          }
          this.getTableData(this.pageSize, 1)
          this.$store.commit("SET_ISRELOADDATA", false);
        }
      },
    },
    filters: {
      toDate: function (val) {
        let result = util.forDateAndTime(val)
        return result
      }
    },
    created() {
      this.getCourseType()
      let status = util.getQuery('status')
      if(!status && status != 0) {
        this.searchData.status = null
      }else {
        this.searchData.status = status
      }
    },
    mounted () {
      if(this.sub == false){
        this.getTableData(this.pageSize, 1)
      }
    },
    methods: {
      //获取课程列表
      getCourseType() {
        coursetype().then(res =>{
          if(res.code == 200){
            this.courseTypeList = res.data
          } else {
            this.tipsBox(res.msg, 'error')
          }
        })
      },

      radioChange(val) {
        this.getTableData(this.pageSize, 1)
      },
      setRole (key) {
        return util.selectTitle(this.power, key)
      },
      //获取tabel数据
      getTableData (pageSize, pageNum) {
        let data = Object.assign({},this.searchData,{
          pageSize: pageSize,
          pageNum: pageNum,
          companyId: this.merchantId,
        })
        courseList(data).then(res => {
          if (res.code == 200) {
            this.tableData = res.data.list
            this.total = res.data.totalRecord
          }else {
            this.tipsBox(res.msg, 'error')
          }
        })
      },
      //打开弹框
      openDialog(type, id, priorityRating = '') {
        this.currentItem = id
        this.dialogType = type
        this.dialogValue.priority = priorityRating
        this.courseStopVisible = true
      },
      // 下架 or 修改权重
      confirmDialog() {
        let that = this
        switch (this.dialogType) {
          //下架
          case 1:
            offlineAdvCourse({
              id: that.currentItem,
              cause: that.dialogValue.case
            }).then(res =>{
              if(res.code == 200){
                this.getTableData(this.pageSize, 1)
                this.tipsBox('下架成功', 'success')
                this.cancel()
              } else {
                this.tipsBox(res.msg, 'error')
              }
            })
            break;
            //修改权重
          case  2:
            this.$refs.ratingPriority.validate((valid) => {
              if (valid) {
                priorityUpd({
                  id: that.currentItem,
                  priorityRating: that.dialogValue.priority
                }).then(res =>{
                  if(res.code == 200){
                    this.getTableData(this.pageSize, 1)
                    this.tipsBox('修改成功', 'success')
                    this.cancel();
                  }else {
                    this.tipsBox(res.msg, 'error')
                  }
                })
              }
            })
            break;
        }
      },
      //取消下架或者修改权重
      cancel() {
        this.currentItem = null
        this.dialogType = null
        this.courseStopVisible = false
        if(this.dialogType == 1){
          this.dialogValue.case = ''
        }else {
          this.dialogValue.priority = null
          this.$refs.ratingPriority.clearValidate()
        }
      },
      //删除课程
      deleCourse(id) {
        this.$confirm('确定要删除该条课程吗?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          delCourse(id).then(res =>{
            if(res.code == 200){
              this.getTableData(this.pageSize, 1)
              this.tipsBox('删除成功', 'success')
            }else {
              this.tipsBox(res.msg, 'error')
            }
          })
        }).catch(() => {});
      },
      //路由跳转详情页
      routerPush (handle, targetId = '') {
        util.routerTo('/app-management/online-classroom/onlineClassroom-list/onlineClassroom-details',{
          handle: handle,
          targetId: targetId,
        })
      },
      // 更改每页条数
      handleSizeChange(val) {
        this.pageSize = val;
        this.getTableData(val, this.pageNum);
      },
      handleCurrentChange(val) {
        this.getTableData(this.pageSize, val);
      },
      //字符串过滤
      replace(obj,key) {
        let that = this
        let event = event || window.event
        if(event.keyCode == 13){
          setTimeout(()=>{
            that.validItem(obj,key);
          },100);
        } else {
          that.validItem(obj,key);
        }
      },
      validItem(obj,key){
        let res = ''
        switch (key) {
          case 'priority':
            res = util.replaceNumber(obj[key]);
            break;
        }
        this.$set(obj,key,res);
      },
      //鼠标移入
      mouseEnter(index, status){
        if(status != 2){
          return;
        }
        this.isActive = index;
      },
      // 鼠标移出
       mouseLeave(){
        this.isActive=null;
        },
      //提示框
      tipsBox(txt, type) {
        this.$message({
          message: txt,
          type: type
        });
      },
    }
  }
</script>
<style lang="less" scoped>
  .online-classroom{
    position: absolute;
    top: 70px;
    left: 11px;
    right: 11px;
    bottom: 10px;
    // overflow: auto;
    .tableSearchs {
      position: relative;
      margin-top: -10px;
      .el-input__icon {
        position: absolute;
        top: 12px;
        left: 170px;
        z-index: 10;
        width: 25px;
        height: 35px;
      }
    }
    .tips {
      color: darkgray;
      line-height: 20px;
    }
    .courseName-column{
      text-align: left;
      display: flex;
      justify-content: start;
      align-items: center;
      position: relative;
      img{
        display: block;
        width: 100px;
        min-height: 10px;
        margin-right: 10px;
      }
      .courseName-mark{
        color: #fff;
        padding: 10px 20px;
        box-sizing: border-box;
        position: absolute;
        left: 0;
        bottom: 0;
        width: 100%;
        min-height: 30px;
        line-height: 20px;
        background: rgba(0,0,0,.4);
      }
    }
  }
</style>
